package com.xbongbong.formula.qlexpress.operator.math;

import com.alibaba.fastjson.JSON;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.Operator;
import com.ql.util.express.OperatorOfNumber;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * SUMIF(value1, [value2], …, criteria)
 * 统计满足条件的参数个数。
 * 例如：
 * • SUMIF([1,2,3,4], “>2”)，结果为7
 * • SUMIF([1,2,3,4], “!=2”)，结果为8
 * • SUMIF([1,2,3,4], “>=1”)，结果为9
 * @author: wufeng
 * @date: 2018/7/4 10:29
 * @desrcption: 计算累加
 */
public class OperatorSumIf extends Operator {


    public OperatorSumIf(String name){
        this.name = name;
    }

    public OperatorSumIf(String aAliasName, String aName, String errorInfo){
        this.aliasName = aAliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }
    @Override
    public Object executeInner(Object[] list) throws Exception {
        Object sum = 0;
        if (list.length != Constant.LENGTH) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261017);
        }
        Object value = list[0];
        Object condition = list[1];
        List<Object> valueList = new ArrayList<>();
        if (!value.getClass().isArray() && ! (value instanceof List)) {
            valueList.add(value);
        } else {
            valueList = JSON.parseArray(JSON.toJSONString(value), Object.class);
        }
        ExpressRunner runner = new ExpressRunner();
        DefaultContext<String, Object> context = new DefaultContext<String, Object>();

        List<Object> sumList = new ArrayList<>();
        for (int i = 0; i < valueList.size(); i++) {
            StringBuilder str = new StringBuilder();
            str.append(valueList.get(i)).append(condition.toString());
            Object r = runner.execute(str.toString(), context, null, true, false);
            boolean b = r instanceof Boolean ? (Boolean) r : false;
            if (b) {
                sumList.add(valueList.get(i));
            }
        }
        for (int i = 0; i < sumList.size(); i++) {
            sum =  OperatorOfNumber.add(sum, sumList.get(i), true);
        }
        return sum;
    }
}
